import userApi from "@/api/user";
import Layout from "@/views/layout";

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes) {
  // 遍历后台传来的路由字符串，转换为组件对象
  let accessedRouters = routes.filter(router => {
    if (router.component === "Layout") {
      // Layout组件特殊处理
      router.component = Layout;
    } else {
      //处理组件---重点
      router.component = loadView(router.component);
    }
    //存在子集
    if (router.children && router.children.length) {
      router.children = filterAsyncRoutes(router.children);
    }
    return true;
  });
  return accessedRouters;
}

function loadView(view) {
  // 路由懒加载
  return () => import(`@/views/${view}`);
}

const state = {
  routes: [],
  addRoutes: []
};

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes;
  }
};

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes;
      userApi.getMenu({}).then(response => {
        const { data } = response;
        accessedRoutes = filterAsyncRoutes(data.route);
        commit("SET_ROUTES", accessedRoutes);
        resolve(accessedRoutes);
      });
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
